package com.zw.pdm.module.craft.service;

import com.zw.pdm.entity.basic.Dept;
import com.zw.pdm.entity.com.ComTaskName;
import com.zw.pdm.entity.com.DsnTaskCommon;
import com.zw.pdm.entity.craft.CraMakeDetail;
import com.zw.pdm.entity.craft.CraMakeSheet;
import com.zw.pdm.entity.craft.CraReleaseDetail;
import com.zw.pdm.entity.craft.CraTaskDetail;
import com.zw.pdm.entity.production.*;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.craft.mapper.CraftReceiveMapper;
import com.zw.pdm.module.craft.mapper.CraftReleaseMapper;
import com.zw.pdm.module.craft.model.CarMakeResultModel;
import com.zw.pdm.module.craft.model.ChuShiHuaModel;
import com.zw.pdm.module.craft.model.ServiceTaskModel;
import com.zw.pdm.module.craft.model.TaskStatusModel;
import com.zw.pdm.module.craft.repository.CraftMakeSheetRepository;
import com.zw.pdm.module.craft.repository.CraftTaskDetaiRepository;
import com.zw.pdm.module.designtask.repository.DsnTaskCommonRepository;
import com.zw.pdm.module.report.mapper.ChangeMapper;
import com.zw.pdm.module.report.mapper.PlanMapper;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Description:
 * @Author: China.sgl
 * @Date: 2019/12/6 08:42
 */
@Service
@SuppressWarnings("all")
public class CraftReleaseService {

    @Autowired
    private CraftReleaseMapper craftReleaseMapper;
    @Autowired
    private ChangeMapper changeMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private CraftTaskDetaiRepository craftTaskDetaiRepository;
    @Autowired
    private DsnTaskCommonRepository dsnTaskCommonRepository;
    @Autowired
    private CraftMakeSheetRepository craftMakeSheetRepository;

    /**
     * 按部门ID查询所有科室
     */
    public List<Dept> findSectionByDeptId(Integer pid) {
        return craftReleaseMapper.findSectionByDeptId(pid);
    }

    /**
     * 查询工艺科室
     *
     * @param pid
     * @return
     */
    public List<Dept> findCraftSectionByDeptId(Integer pid) {
        return craftReleaseMapper.findCraftSectionByDeptId(pid);
    }

    /**
     * 查询待分配列表
     *
     * @param serviceTaskModel
     * @return
     */
    public List<ServiceTaskModel> findWithCraftQuery(ServiceTaskModel serviceTaskModel) {
        return craftReleaseMapper.findWithCraftQuery(serviceTaskModel);

    }

    /**
     * 分配任务
     *
     * @param makeId
     * @param sectionId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean releaseTask(Integer makeId, Integer[] sectionId) {
        List<CraMakeSheet> craMakeSheetlList = selectCraMakeSheetById(makeId);
        Integer proId = craMakeSheetlList.get(0).getProId();
        if (craMakeSheetlList.get(0).getIsRelease() == 1) {
            //删除分配任务明细
            delCraReleaseDetail(makeId);
            //修改工艺主表状态，反写分配后需要字段
            updateCraMakeSheet(makeId, sectionId, proId);
            logService.saveLog("任务分配修改", "工艺制作件清单主表ID：" + makeId);
        } else {
            //修改工艺主表状态，反写分配后需要字段
            updateCraMakeSheet(makeId, sectionId, proId);
            //获取此项目是否创建过任务
            int count = craftReleaseMapper.selectCountByProId(proId);
            if (count == 0) {

                //生成任务（工艺编制，成本信息输出，原材料计划，外协计划）初始状态都为 未开始
                CraTaskDetail craTaskDetail = savaCraTaskDetail(proId);
                //获取com_task_name 表中所有工艺任务对象
                List<ComTaskName> comTaskNameList = selectCraTaskByCommonId(68);
                //生成dsn_task_common 表任务明细，根据工艺任务明细，生成对应部分的所有任务
                saveDsnTaskCommon(craMakeSheetlList.get(0), comTaskNameList, craTaskDetail);
            }
            logService.saveLog("任务分配", "工艺制作件清单主表ID：" + makeId);
        }
//        updateDsnTaskCommon(craMakeSheetlList.get(0));

        return true;
    }

    /**
     * 生成dsn_task_common 表任务明细，根据工艺任务明细，生成对应部分的所有任务
     *
     * @param craMakeSheet
     * @param comTaskNameList
     * @param craTaskDetail
     */
    private void saveDsnTaskCommon(CraMakeSheet craMakeSheet, List<ComTaskName> comTaskNameList, CraTaskDetail craTaskDetail) {
        for (int i = 0; i < comTaskNameList.size(); i++) {
            DsnTaskCommon dsnTaskCommon = new DsnTaskCommon();
            dsnTaskCommon.setComTaskNameId(comTaskNameList.get(i).getId());
            dsnTaskCommon.setComTaskName(comTaskNameList.get(i).getName());
            dsnTaskCommon.setStatus(1);
            dsnTaskCommon.setProCode(craMakeSheet.getProCode());
            dsnTaskCommon.setIsDel(0);
            dsnTaskCommon.setProName(craMakeSheet.getProName());
            dsnTaskCommon.setProId(craMakeSheet.getProId());
//            dsnTaskCommon.setProPart(craMakeSheet.getPart());
//            dsnTaskCommon.setProPartId(craMakeSheet.getProId());
            dsnTaskCommon.setCraTaskDetailId(craTaskDetail.getId());
//            dsnTaskCommon.setSpecial(craMakeSheet.getSpecial());
//            dsnTaskCommon.setSpecialId(craMakeSheet.getSpecialId());
            dsnTaskCommonRepository.save(dsnTaskCommon);
        }
    }

    /**
     * 获取com_task_name 表中所有工艺任务对象
     *
     * @param commonId
     * @return
     */
    private List<ComTaskName> selectCraTaskByCommonId(Integer commonId) {
        return craftReleaseMapper.selectCraTaskByCommonId(commonId);
    }

    /**
     * 生成任务（工艺编制，成本信息输出，原材料计划，外协计划）
     *
     * @param proId
     */
    private CraTaskDetail savaCraTaskDetail(Integer proId) {
        CraTaskDetail craTaskDetail = new CraTaskDetail();
        craTaskDetail.setProId(proId);
        craTaskDetail.setCostStatus(1);
        craTaskDetail.setCraftStatus(1);
        craTaskDetail.setMaterialStatus(1);
        craTaskDetail.setOutsourcingStatus(1);
        craTaskDetail.setIsDel(0);
        return craftTaskDetaiRepository.save(craTaskDetail);

    }

    /**
     * 分配任务
     *
     * @param makeId
     * @param sectionId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean releaseTask1(Integer makeId, Integer[] sectionId) {
        List<CraMakeSheet> craMakeSheetlList = selectCraMakeSheetById(makeId);
        Integer proId = craMakeSheetlList.get(0).getProId();
        if (craMakeSheetlList.get(0).getIsRelease() == 1) {
            delCraReleaseDetail(makeId);
            updateCraMakeSheet(makeId, sectionId, proId);
            logService.saveLog("任务分配修改", "工艺制作件清单主表ID：" + makeId);
        } else {
            updateCraMakeSheet(makeId, sectionId, proId);
            logService.saveLog("任务分配", "工艺制作件清单主表ID：" + makeId);
        }
        updateDsnTaskCommon(craMakeSheetlList.get(0));

        return true;
    }

    /**
     * 通过ID 查询制作件主表
     *
     * @param id
     * @return
     */
    public List<CraMakeSheet> selectCraMakeSheetById(Integer id) {
        return craftReleaseMapper.selectCraMakeSheetById(id);
    }

    /**
     * 任务分配后，主表信息修改
     *
     * @return
     */
    public Integer updateCraMakeSheet(Integer id, Integer[] sectionId, Integer proId) {
        String setion = "";
        for (int i = 0; i < sectionId.length; i++) {

            Dept dept = selectDetpSetionName(sectionId[i]);
            if (setion.equals("")) {

                setion += dept.getName();
            } else {
                setion += "," + dept.getName();
            }
            CraReleaseDetail craReleaseDetail = new CraReleaseDetail();
            craReleaseDetail.setProId(proId);
            craReleaseDetail.setDistributionName(ShiroUtils.getUser().getName());
            craReleaseDetail.setDistributionTime(new Date());
            craReleaseDetail.setSectionId(sectionId[i]);
            craReleaseDetail.setSectionName(dept.getName());
            craReleaseDetail.setSheetId(id);
            craReleaseDetail.setIsDel(0);
            craReleaseDetail.setIsSuccess(0);
            insertCraReleaseDetail(craReleaseDetail);
        }
        CraMakeSheet craMakeSheet = new CraMakeSheet();
        craMakeSheet.setId(id);
        craMakeSheet.setDeptName(setion);
        craMakeSheet.setDistributionName(ShiroUtils.getUser().getName());
        craMakeSheet.setDistributionTime(new Date());
        craMakeSheet.setIsRelease(1);
        craftReleaseMapper.updateCraMakeSheet(craMakeSheet);
        return 1;
    }

    /**
     * 按ID 查询
     *
     * @param id
     * @return
     */
    public Dept selectDetpSetionName(Integer id) {
        return craftReleaseMapper.selectDetpSetionName(id);
    }

    /**
     * 对象插入分配明细表数据
     *
     * @param craReleaseDetail
     * @return
     */
    public Integer insertCraReleaseDetail(CraReleaseDetail craReleaseDetail) {
        return craftReleaseMapper.insertCraReleaseDetail(craReleaseDetail);
    }

    /**
     * 根据部分ID 删除已经分配的任务
     *
     * @param craReleaseDetail
     * @return
     */
    public Integer delCraReleaseDetail(Integer sheetId) {
        return craftReleaseMapper.delCraReleaseDetail(sheetId);
    }

    /**
     * 更新共用工艺表数据（dsn_task_common）
     */
    public void updateDsnTaskCommon(CraMakeSheet craMakeSheet) {
        List<CraReleaseDetail> craReleaseDetailList = craftReleaseMapper.selectCtaReleaseDetailAndDsnTaskCommon(craMakeSheet.getProId());
        List<ComTaskName> comTaskNameList = craftReleaseMapper.selectComtaskNameByDictCommonId(68);
        DsnTaskCommon dsnTaskCommon = new DsnTaskCommon();
        dsnTaskCommon.setProId(craMakeSheet.getProId());
        dsnTaskCommon.setProCode(craMakeSheet.getProCode());
        dsnTaskCommon.setProName(craMakeSheet.getProName());
        dsnTaskCommon.setStatus(1);
        dsnTaskCommon.setIsDel(0);
        if (craReleaseDetailList.size() > 0 && comTaskNameList.size() > 0) {
            for (int i = 0; i < craReleaseDetailList.size(); i++) {
                dsnTaskCommon.setDeptId(craReleaseDetailList.get(i).getSectionId());
                for (int j = 0; j < comTaskNameList.size(); j++) {
                    dsnTaskCommon.setComTaskNameId(comTaskNameList.get(j).getId());
                    dsnTaskCommon.setComTaskName(comTaskNameList.get(j).getName());
                    addDsnTaskCommon(dsnTaskCommon);
                }

            }
        }
        List<DsnTaskCommon> dsnTaskCommonList = craftReleaseMapper.selectDsnTaskCommonAndCraReleaseDetail(craMakeSheet.getProId());
        if (dsnTaskCommonList.size() > 0) {
            for (int i = 0; i < dsnTaskCommonList.size(); i++) {

                delDsnTaskCommon(dsnTaskCommonList.get(i));
            }
        }
    }

    /**
     * 插入数据DsnTaskCommon
     *
     * @param dsnTaskCommon
     * @return
     */
    public Integer addDsnTaskCommon(DsnTaskCommon dsnTaskCommon) {
        return craftReleaseMapper.addDsnTaskCommon(dsnTaskCommon);
    }

    public Integer delDsnTaskCommon(DsnTaskCommon dsnTaskCommon) {
        return craftReleaseMapper.delDsnTaskCommon(dsnTaskCommon);
    }

    /**
     * 重新分配任务按钮加载项
     *
     * @param sheetId
     * @return
     */
    public List<CraReleaseDetail> selTaskList(Integer sheetId) {
        return craftReleaseMapper.selTaskList(sheetId);
    }

    /**
     * 初始化代码
     *
     * @return
     */
    public boolean chushihuayuanshi() {
        //获取com_task_name 表中所有工艺任务对象
        List<ComTaskName> comTaskNameList = selectCraTaskByCommonId(68);
        List<CraMakeSheet> craMakeSheetList = craftReleaseMapper.selectMakeSheet();
        for (int i = 0; i < craMakeSheetList.size(); i++) {
            chushihuayiyou(craMakeSheetList.get(i), comTaskNameList);
        }
        return true;
    }

    /**
     * 初始化
     *
     * @param craMakeSheet
     */
    @Transactional(rollbackFor = Exception.class)
    private void chushihuayiyou(CraMakeSheet craMakeSheet, List<ComTaskName> comTaskNameList) {
        CraTaskDetail craTaskDetail = savaCraTaskDetail(craMakeSheet.getProId());
        //生成dsn_task_common 表任务明细，根据工艺任务明细，生成对应部分的所有任务
        saveDsnTaskCommon(craMakeSheet, comTaskNameList, craTaskDetail);
    }

    /**
     * 初始化 看板数据
     *
     * @return
     */
    public boolean chushihua() {
        //获取com_task_name 表中所有工艺任务对象
        List<ComTaskName> comTaskNameList = selectCraTaskByCommonId(68);
        List<ChuShiHuaModel> chuShiHuaModelList = craftReleaseMapper.getVwStatus();
        for (int i = 0; i < chuShiHuaModelList.size(); i++) {

            saveChuShiHuaTable(chuShiHuaModelList.get(i), comTaskNameList);
        }
        return true;
    }

    /**
     * 初始化 项目看板 倒过来数据所有表
     *
     * @param chuShiHuaModel
     */
    @Transactional(rollbackFor = Exception.class)
    private void saveChuShiHuaTable(ChuShiHuaModel chuShiHuaModel, List<ComTaskName> comTaskNameList) {
        //初始化 项目看板 时 保存CraMakeSheet 表
//        CraMakeSheet craMakeSheet = saveCramakeSheet(chuShiHuaModel);
        //初始化 项目看板 时 保存CraTaskDetail 表
//        CraTaskDetail craTaskDetail = saveCraTaskDetail(craMakeSheet, chuShiHuaModel);
        CraTaskDetail craTaskDetail = saveCraTaskDetail(null, chuShiHuaModel);
        //初始化 项目看板 时 保存dsnTaskCommon 表
//        saveDsnTaskCommonDetail(chuShiHuaModel, comTaskNameList, craTaskDetail, craMakeSheet);
        saveDsnTaskCommonDetail(chuShiHuaModel, comTaskNameList, craTaskDetail, null);

    }

    /**
     * 初始化 项目看板 时 保存dsnTaskCommon 表
     *
     * @param chuShiHuaModel
     * @param comTaskNameList
     * @param craTaskDetail
     */
    private void saveDsnTaskCommonDetail(ChuShiHuaModel chuShiHuaModel, List<ComTaskName> comTaskNameList, CraTaskDetail craTaskDetail, CraMakeSheet craMakeSheet) {
        for (int i = 0; i < comTaskNameList.size(); i++) {
            DsnTaskCommon dsnTaskCommon = new DsnTaskCommon();
            dsnTaskCommon.setComTaskNameId(comTaskNameList.get(i).getId());
            dsnTaskCommon.setComTaskName(comTaskNameList.get(i).getName());
            if (comTaskNameList.get(i).getId() == 1) {
                dsnTaskCommon.setStatus(chuShiHuaModel.getSixthStatus() + 1);
            } else if (comTaskNameList.get(i).getId() == 4) {
                dsnTaskCommon.setStatus(3);
            } else {

                dsnTaskCommon.setStatus(chuShiHuaModel.getFifthStatus() + 1);
            }
            dsnTaskCommon.setProCode(chuShiHuaModel.getCode());
            dsnTaskCommon.setIsDel(0);
            dsnTaskCommon.setProName(chuShiHuaModel.getName());
            dsnTaskCommon.setProId(chuShiHuaModel.getId());
//            dsnTaskCommon.setProPart(craMakeSheet.getPart());
//            dsnTaskCommon.setProPartId(craMakeSheet.getProId());
            dsnTaskCommon.setCraTaskDetailId(craTaskDetail.getId());
//            dsnTaskCommon.setSpecial(craMakeSheet.getSpecial());
//            dsnTaskCommon.setSpecialId(craMakeSheet.getSpecialId());
            dsnTaskCommonRepository.save(dsnTaskCommon);
        }
    }

    /**
     * 初始化 项目看板 时 保存CraTaskDetail 表
     *
     * @param craMakeSheet
     * @param chuShiHuaModel
     * @return
     */
    private CraTaskDetail saveCraTaskDetail(CraMakeSheet craMakeSheet, ChuShiHuaModel chuShiHuaModel) {
        CraTaskDetail craTaskDetail = new CraTaskDetail();
        craTaskDetail.setProId(chuShiHuaModel.getId());
        craTaskDetail.setCostStatus(3);
        craTaskDetail.setCraftStatus(chuShiHuaModel.getSixthStatus() + 1);
        craTaskDetail.setMaterialStatus(chuShiHuaModel.getFifthStatus() + 1);
        craTaskDetail.setOutsourcingStatus(chuShiHuaModel.getFifthStatus() + 1);
        craTaskDetail.setIsDel(0);
        return craftTaskDetaiRepository.save(craTaskDetail);
    }

    /**
     * 初始化 项目看板 时 保存CraMakeSheet 表
     *
     * @param chuShiHuaModel
     * @return
     */
    private CraMakeSheet saveCramakeSheet(ChuShiHuaModel chuShiHuaModel) {
        CraMakeSheet craMakeSheet = new CraMakeSheet();
        craMakeSheet.setDrawType(chuShiHuaModel.getProjectClassify());
        craMakeSheet.setProId(chuShiHuaModel.getId());
        craMakeSheet.setProCode(chuShiHuaModel.getCode());
        craMakeSheet.setProName(chuShiHuaModel.getName());
        craMakeSheet.setProNum(chuShiHuaModel.getNum().toString());
        craMakeSheet.setPart(chuShiHuaModel.getProPart());
        craMakeSheet.setPartId(chuShiHuaModel.getProPartId().toString());
        craMakeSheet.setSpecialId(chuShiHuaModel.getSpecialId());
        craMakeSheet.setSpecial(chuShiHuaModel.getSpecial());
        craMakeSheet.setCreatTime(chuShiHuaModel.getCreateTime());
        craMakeSheet.setDistributionTime(chuShiHuaModel.getCreateTime());
        craMakeSheet.setIsRelease(1);
        return craftMakeSheetRepository.save(craMakeSheet);
    }
}
